
#include "EchoClient.h"
#include "Logging.h"

#include <unistd.h>

using namespace muduo;

StdInFd::StdInFd(EchoClient* pEchoClient)
    : muduo::FdEvent(pEchoClient->pMainLoop_, 0),
      pEchoClient_(pEchoClient)
{
    
}

StdInFd::~StdInFd()
{
    updateFdEvent(DelEvent);
}

void StdInFd::handleRead(muduo::Timestamp& receiveTime)
{
    char buf[64]={0};
    ::read(fd_, buf, sizeof(buf)-1);
    
    TcpLinkSPtr tcpLinkSPtr = pEchoClient_->tcpLinkWPtr_.lock();
    if (tcpLinkSPtr)
    {
        tcpLinkSPtr->send(buf);
    }
}

EchoClient::EchoClient(muduo::EventLoop* pMainLoop, 
                       const muduo::InetAddress& serverAddr)
    : pMainLoop_(pMainLoop),
      tcpClient_(serverAddr, "EchoClient", pMainLoop),
      stdIn_(this)
{
    stdIn_.enableReading(AddEvent);
    
    TcpClient::newConnectionCallback_ = std::bind(&EchoClient::newConnection, 
                                                this, 
                                                std::placeholders::_1);

    TcpClient::delConnectionCallback_ = std::bind(&EchoClient::delConnection, 
                                                this, 
                                                std::placeholders::_1);
                                                
    TcpClient::rcvMessageCallback_    = std::bind(&EchoClient::rcvMessage, 
                                                this, 
                                                std::placeholders::_1, 
                                                std::placeholders::_2, 
                                                std::placeholders::_3); 
}

void EchoClient::start()
{
    tcpClient_.connect();
}

void EchoClient::newConnection(const muduo::TcpLinkSPtr& conn)
{
    tcpLinkWPtr_ = conn;
}

void EchoClient::delConnection(const muduo::TcpLinkSPtr& conn)
{

}

void EchoClient::rcvMessage(const muduo::TcpLinkSPtr& conn,
                            muduo::Buffer* buf, muduo::Timestamp time)
{
    std::string msg(buf->retrieveAllAsString());
    muduo::LOG_INFO("received %d bytes : %s", msg.size(), msg.c_str());
}


